package top.leix.springdemo.intercepter;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import top.leix.springdemo.Utils.TokenUtil;
import top.leix.springdemo.annotation.AuthAccess;
import top.leix.springdemo.exception.ServiceException;
import top.leix.springdemo.mapper.StudentMapper;
import top.leix.springdemo.pojo.Student;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class TokenInterceptor implements HandlerInterceptor {

    private final StudentMapper studentMapper;

    public TokenInterceptor(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //如果打了权限注解@AuthAccess，直接通过
        if(handler instanceof HandlerMethod) {
            AuthAccess annotation = ((HandlerMethod) handler)
                    .getMethodAnnotation(AuthAccess.class);
            if(annotation != null) {
                return true;
            }
        }

        String token = "";
                response.setCharacterEncoding("utf-8");
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
            // 如果不是，我们就把token拿到，用来做判断
        }
        // header里面的字段名取决于前端放置的字段名
        token = request.getHeader("Token");
        if(StrUtil.isBlank(token)){
            token = request.getParameter("Token"); //url参数中拿， ?token=XXXX
        }
        System.out.println("用户传入的token:" + token);
        String auToken = request.getHeader("Authorization");
        System.out.println( "auToken:"+ auToken);
        //开始认证
        if(StrUtil.isBlank(token)){
            throw new  ServiceException("401","未登录token = null");
        }
        String userAccount;
        try{
            userAccount = JWT.decode(token).getClaim("userAccount").asString();
        }catch (JWTDecodeException j){
            throw new ServiceException("401","未登录2");
        }
        System.out.println(userAccount);
        Student student = studentMapper.selectOne(new QueryWrapper<Student>()
                        .eq("userAccount",userAccount));
        System.out.println(student);
        if(student ==null){
            throw new ServiceException("401","未知用户尝试登录");
        }
        if (token != null) {
            boolean result = TokenUtil.verify(token);
            if (result) {
                System.out.println("通过拦截器");
                return true;
            }
        }
        return false;

    }

}